<template>
  <div style="height:100%;">
     <mapBoxViewer 
        ref="refMap" 
        :searchPanel="false"
        @onInit="initMap"
        @onDrag="openPupop"
        @onDragEnd="openPupop"
        @onZoom="onChangeZoom"
        @onZoomEnd="onChangeZoom"
        :location="landInfo" />
     <!-- <PoiPopup v-if="showPop"  :popOption="popObjct" @click="btnOpen" @onClose="closePopup"  /> -->
  </div>
</template>

<script setup>
import {ref,onMounted,watch } from "vue"
import {useUserStore} from '@/pinia/modules/user'
import mapBoxViewer from "@/components/gisMapBox/index.vue";
import PoiPopup from '@/components/gisMapBox/components/PoiPopup.vue';
import {getLandMiniList,getFarmCount} from '@/api/gis'
import {getPageList} from '@/utils/common'
const userStore = useUserStore()
const props = defineProps({
  detail:{
      type:Object,
      default:{}
  },
  landInfo:{
    type:Object,
    default:{}
  },
  landGroupId:{
    type:Object,
    default:''
  }
})

const emit = defineEmits(['onOpen','complete'])
let mapView = null
let farmLandId=null
const dataList = ref([])
const refMap = ref(null)
const showPop = ref(false)
const popObjct = ref({})
const landInfoData = ref({})
watch(()=>props.landInfo,()=>{
landInfoData.value = props.landInfo
openPupop()
showPop.value = true
changeLandColors(props.landInfo?.farmLandId)
})

watch(()=>props.landGroupId,()=>{
   updateData()
})


onMounted(()=>{
})

const openPupop =()=>{
  if(!showPop.value){return}
  let item = landInfoData.value 
  const point = refMap.value.getWindXY(landInfoData.value.longitude,landInfoData.value.latitude)
  const popOption = {
        title:item.farmLandNo,
        farmId:item.farmId,
        companyId:item.companyId,
        farmLandId:item.farmLandId,
        pic:item.pic,
        screenX: point.left-150,
        screenY: point.top-120,
        visible:true,
        mapX: item.longitude,
        mapY: item.latitude,
        footer:false,
        values: [
            {
                label: '地块名称',
                value: item.farmLandName
            },
            {
                label: '地块面积',
                value:  Number(item.mapAreaSize||item.mapareasize||0).toFixed(2)+'亩'
            },
            {
                label: '地块类型',
                value: item.landTypeName||item.landtypename||'--'
            },
            {
                label: '作物类型',
                value: (item.cropName||'--')+','+(item.cropSeriesName||'--')
            },
            {
                label: '地块位置',
                value: item.locationAddress||item.locationaddress||'--'
            },
        ],
        footerList:[
          {
              btnText:'编辑',
              icon:'vxe-icon-edit',
              farmId:item.farmId,
              color:'#409eff',
              farmLandId:item.farmLandId,
              type:1,
          },
          {
              btnText:'查看详情',
              icon:'vxe-icon-file-txt',
              farmId:item.farmId,
              color:'#25c289',
              farmLandId:item.farmLandId,
              type:2
          }
      ],
      ...item
  }
  popObjct.value = popOption
}

const initMap =async (map)=>{
   mapView = map
   const res = await getFarmCount({companyId:userStore.userInfo.companyId,farmId:userStore.userInfo.farmId})
   if(res.success){
      let pages =getPageList(res.data?.farmLandCount||6000)
      let params ={
        farmId:userStore.userInfo.farmId, 
        companyId:userStore.userInfo.companyId
      }
      pages.forEach(async (item)=>{
          window.setTimeout(async () => {
              let res =await getLandMiniList({...params,...item})
              if(res?.success){
                  dataList.value =dataList.value.concat(res.data.filter((item)=>item.geom!=null))
                  emit('complete',dataList.value)
                  if(item.page==1){
                      addLandList()
                  }else{
                      updateData()
                  }
              }
              }, item.page==1?0:(item.page*200));
      })
   }
}

const updateData =()=>{
  let filterList =dataList.value.filter((item)=>{
   return (item.landGroupId == props?.landGroupId ||props?.landGroupId=='all')}).map((item)=> {
                if(item?.geom && item.geom!='null' && item.geom !=null){
                  return {
                      type: 'Feature',
                      id:item.farmLandId,
                      properties: {
                          description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                          lineColor:'#25c289',
                          lineWidth:3,
                          ...item
                      },
                      geometry: {
                          type: 'Polygon',
                          coordinates: [JSON.parse(item.geom||'[]')]
                      }
                  }
          }
  })
  mapView.getSource('polygons-source').setData({type: 'FeatureCollection', features:filterList})
  let centerList =[]
  filterList.forEach((item)=>{
        centerList.push([Number(item.properties.locationLongitude),Number(item.properties.locationLatitude)])
    })
    refMap.value.locationCenter(centerList)
}

const addSourceData =()=>{
       mapView.addSource('polygons-source', {
          type: 'geojson',
          data: {
              type: 'FeatureCollection',
              features: dataList.value.map((item)=> {
                if(item?.geom && item.geom!='null' && item.geom !=null){
                  return {
                      type: 'Feature',
                      id:item.farmLandId,
                      properties: {
                          description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                          lineColor:'#25c289',
                          lineWidth:3,
                          ...item
                      },
                      geometry: {
                          type: 'Polygon',
                          coordinates: [JSON.parse(item.geom||'[]')]
                      }
                  }
                }
              })
          }
  })
}

const addLandList =()=>{
     addSourceData()
     //添加线条
     mapView.addLayer({
          'id': 'polygons-layer-line',
          'type': 'line',
          'source': 'polygons-source',
          'layout': {},
          'paint': {
              'line-color': ['get', 'lineColor'],
              'line-width': ['get', 'lineWidth']
          }
  })

  // 添加多边形图层-图层
  mapView.addLayer({
          'id': 'polygons-layer-fill',
          'type': 'fill',
          'source': 'polygons-source',
          'paint': {
          'fill-opacity': 0.5,
            'fill-color': [
              'case',
              ['boolean', ['feature-state', 'click'], false],
              '#59e3b1',
              'rgba(255, 255, 255, 0)']
            },
            "interactive": true
      })

      // 添加多边形图层-文字
      mapView.addLayer({
          'id': 'polygons-layer-text',
          'type': 'symbol',
          'source': 'polygons-source',
          layout: {
              'text-field': ['get', 'description'],
              'text-size': 13,
              'text-anchor': 'center',
              'visibility': 'none',
              "text-translate": [0, 1],
              "text-translate-anchor": "map",
              'text-offset': [0, 0],
          },
          paint: {
            'text-color': '#ffffff',
             "text-halo-color": "#000000",
             "text-halo-width": 1 
          },
          metadata: {
              'renderedOnServer': false
          }
      });
  

   mapView.on('click','polygons-layer-fill',(e)=> {
      let item = e.features[0]
      landInfoData.value = {
        ...item?.properties,
        longitude:item?.properties?.locationLongitude,
        latitude:item?.properties?.locationLatitude
      }
      showPop.value = true
      changeLandColors(item.id)
      openPupop()
    })


  //  mapView.on('mouseenter', 'polygons-layer-fill',(e)=> {
  //       mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');
  // })
  
  //  mapView.on('mouseleave', 'polygons-layer-fill', (e)=> {
  //       mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
  // })
}
const changeLandColors =(Id)=>{
  if(farmLandId){
          mapView.setFeatureState({source: 'polygons-source', id:farmLandId },{ click: false });
      }
  farmLandId=Id
  mapView.setFeatureState({source: 'polygons-source', id: Id },{ click: true });
}
const closePopup =()=>{
  if(farmLandId){
      mapView.setFeatureState({source: 'polygons-source', id:farmLandId },{ click: false });
      farmLandId=null
  }
  showPop.value = false
}

const onChangeZoom =(row)=>{
  if(row.currentZoom<17){
        showPop.value = false
        mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
    }else{
        mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');
    }
  // openPupop()
}
const btnOpen =(val)=>{
 emit('onOpen',val)
}

</script>

<style lang="scss" scoped>

</style>